import { defineStore } from 'pinia'
import { wxLogin as wxLoginApi, getMerchantEntryStatus } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    isLogin: false,
    userInfo: null,
    accessToken: '',
    refreshToken: '',
    merchantId: '',
    deliveryFeeRatio: 0
  }),
  getters: {
    nickname: (state) => state.userInfo?.nickname || '商家',
    avatar: (state) => state.userInfo?.avatar || '/static/images/default-avatar.png',
    loggedIn: (state) => state.isLogin && state.accessToken
  },
  actions: {
    /**
     * 静默登录，获取商家用户信息
     * @returns {Promise<Object>} 商家用户信息
     */
    login() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            this.wxLogin(loginRes.code)
              .then(resolve)
              .catch(reject)
          },
          fail: reject
        })
      })
    },
    /**
     * 微信登录
     * @param {string} code
     * @returns {Promise<Object>}
     */
    async wxLogin(code) {
      try {
        const { data } = await wxLoginApi(code)
        this.isLogin = true
        this.userInfo = data.userInfo
        this.accessToken = data.accessToken
        this.refreshToken = data.refreshToken
        this.merchantId = data.merchantId
        this.deliveryFeeRatio = data.deliveryFeeRatio || 0
        uni.setStorageSync('accessToken', this.accessToken)
        uni.setStorageSync('refreshToken', this.refreshToken)
        uni.setStorageSync('merchantId', this.merchantId)
        uni.setStorageSync('deliveryFeeRatio', this.deliveryFeeRatio)
        uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))
        // 登录成功后检查入驻状态
        await this.checkMerchantEntryStatus()
      } catch (error) {
        console.error('微信登录失败:', error)
        throw error
      }
    },
    /**
     * 检查商户入驻状态并跳转
     */
    async checkMerchantEntryStatus() {
      if (!this.userInfo?.id) return
      try {
        const { data } = await getMerchantEntryStatus(this.userInfo.id)
        switch (data.status) {
          case '未入驻':
            uni.redirectTo({ url: '/pages/entry/apply' })
            break
          case '审核中':
            uni.redirectTo({ url: '/pages/entry/pending' })
            break
          case '审核拒绝':
            uni.redirectTo({ url: `/pages/entry/reject?reason=${encodeURIComponent(data.rejectReason || '')}` })
            break
            case '审核通过但未完善':
              uni.redirectTo({ url: '/pages/shop/edit' })
              break 
            case '审核通过且已完善':
            // 正常进入主页面
            uni.switchTab({ url: '/pages/index/index' })
            break
        }
      } catch (e) {
        console.error('入驻状态查询失败', e)
      }
    },
    /**
     * 退出登录
     */
    logout() {
      this.isLogin = false
      this.userInfo = null
      this.accessToken = ''
      this.refreshToken = ''
      this.merchantId = ''
      this.deliveryFeeRatio = 0
      uni.removeStorageSync('accessToken')
      uni.removeStorageSync('refreshToken')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('merchantId')
      uni.removeStorageSync('deliveryFeeRatio')
    },
    /**
     * 检查是否有登录数据
     * @returns {boolean} 是否有完整的登录数据
     */
    checkLoginData() {
      const accessToken = uni.getStorageSync('accessToken')
      const refreshToken = uni.getStorageSync('refreshToken')
      const userInfoStr = uni.getStorageSync('userInfo')
      const merchantId = uni.getStorageSync('merchantId')
      
      return !!(accessToken && refreshToken && userInfoStr && merchantId)
    },
    
    /**
     * 恢复登录状态
     * @returns {Promise<void>}
     */
    async restoreLoginState() {
      const accessToken = uni.getStorageSync('accessToken')
      const refreshToken = uni.getStorageSync('refreshToken')
      const userInfoStr = uni.getStorageSync('userInfo')
      const merchantId = uni.getStorageSync('merchantId')
      const deliveryFeeRatio = uni.getStorageSync('deliveryFeeRatio')

      try {
        this.accessToken = accessToken
        this.refreshToken = refreshToken
        this.userInfo = JSON.parse(userInfoStr)
        this.merchantId = merchantId
        this.deliveryFeeRatio = deliveryFeeRatio || 0
        this.isLogin = true
        // 恢复登录状态后检查入驻状态
        await this.checkMerchantEntryStatus()
      } catch (e) {
        console.error('恢复登录状态失败:', e)
        this.logout()
        throw e
      }
    },
    
    /**
     * 初始化用户状态（简化版，仅用于兼容）
     */
    initUserState() {
      // 简化的初始化方法，主要用于兼容现有代码
      if (this.checkLoginData()) {
        return this.restoreLoginState()
      }
      return Promise.resolve()
    },
    /**
     * 刷新token后更新本地token
     */
    updateToken({ accessToken, refreshToken }) {
      this.accessToken = accessToken
      this.refreshToken = refreshToken
      uni.setStorageSync('accessToken', accessToken)
      uni.setStorageSync('refreshToken', refreshToken)
    }
  }
})